<script setup>
import { useStore } from 'vuex';
import service from '@/utils/request.utils';
import { ref } from 'vue';
import { computed, onBeforeMount } from 'vue';
import { getCookie } from '@/utils/cookie.utils';
import { ElMessage } from 'element-plus';
import { RESPONSE_MESSAGE } from '@/constant/response';

const upload = ref(null)

const store = useStore()

const avatarUploadShow = ref(import.meta.env.VITE_STATIC_ADDR + "avatar/" + store.getters.getAvatar);
const uploadAvatar = ref(false)
const drawer = ref(false)
const token = ref({})
const uploadUrl = "/upload/avatar"
let avatarFile = null

onBeforeMount(() => {
    token.value = {
        "authorization": getCookie("token")
    }
})

const user = computed(() => {
    return store.getters.getUser
})

const updateForm = ref({
    nickname: store.getters.getUser['nickname'],
    password: store.getters.getUser["password"]
})


const avatar = computed(() => {
    return import.meta.env.VITE_STATIC_ADDR + "avatar/" + store.getters.getAvatar;
})

async function uploadAvatarFile() {
    drawer.value = true
}

// 注意不能直接给uploadAvatar赋值
function mouseenterHandle() {
    uploadAvatar.value = true
}

function onmouseleaveHandle() {
    uploadAvatar.value = false
}

const beforeAvatarUpload = (file) => {
    console.log("beforeAvatarUpload", file)
    if (file.raw.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    } else if (file.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    avatarFile = file
    avatarUploadShow.value = URL.createObjectURL(file.raw)
    return true
}


const submitUpload = async () => {
    console.log(avatarFile)
    let formData = new FormData()
    formData.append("file", avatarFile.raw)
    let res = await service.post(uploadUrl, formData, {
        "Content-Type": "multipart/form-data;charset=utf-8"
    })
    console.log(res)

    if (res.status != 200) {
        ElMessage({
            message: '操作失败: ' + res.status,
            type: 'error'
        })
        return
    }

    if (res.data.code != '0') {
        console.log(res.data)
        ElMessage({
            message: RESPONSE_MESSAGE[res.data.code],
            type: "warning"
        })
        return
    } else {
        ElMessage({
            message: RESPONSE_MESSAGE[res.data.code],
            type: "warning"
        })

        store.commit("updateAvatar", res.data.data["avatar"])

        return
    }
}

async function submitForm() {

    if (user.value["nickname"] == updateForm.value["nickname"] && user.value["password"] == updateForm.value["password"]) {
        ElMessage.info("没有需要更新的信息")
        return
    }

    const form = {}

    if (user.value["nickname"] != updateForm.value["nickname"]) {
        form["nickname"] = updateForm.value["nickname"]
    }

    if (user.value["password"] != updateForm.value["password"]) {
        form["password"] = updateForm.value["password"]
    }

    form["userId"] = store.getters.getUser["id"]
    console.log(store.getters.getUser["id"])
    console.log(form)
    let res = await service.post("/user/update", form)
    console.log(res)

    if (res.status != 200) {
        ElMessage({
            message: '操作失败: ' + res.status,
            type: 'error'
        })
        return
    }

    if (res.data.code != '0') {
        console.log(res.data)
        ElMessage({
            message: RESPONSE_MESSAGE[res.data.code],
            type: "warning"
        })
        return
    } else {
        ElMessage({
            message: RESPONSE_MESSAGE[res.data.code],
            type: "success"
        })

        if ("nickname" in form) {
            store.commit("updateNickname", form["nickname"])
        }

        if ("password" in form) {
            store.commit("updatePassword", form["password"])
        }

        return
    }
}

</script>
<template>
    <el-drawer v-model="drawer" title="更换头像" :with-header="true">
        <div id="drawer">
            <div id="uploadAvatar">
                <el-avatar :src="avatarUploadShow" style="width:100%;height:100%;" />
            </div>
            <div>
                <el-upload ref="upload" class="avatar-uploader" :headers="token" :action="uploadUrl" :limit="1"
                    :auto-upload="false" :http-request="uploadFile" :on-change="beforeAvatarUpload">
                    <template #trigger>
                        <el-button type="primary">选择头像</el-button>
                    </template>
                    <el-button style="margin-left: 10px" type="success" @click="submitUpload">
                        上传
                    </el-button>
                </el-upload>
            </div>
        </div>
    </el-drawer>
    <div id="outer">
        <div>
            <el-form :model="form" label-width="auto" style="max-width: 600px; position: relative; bottom: 1em;">
                <div id="avatar" @mouseenter="mouseenterHandle" @mouseleave="onmouseleaveHandle">
                    <el-avatar :src="avatar" style="width:100%;height:100%;" />
                    <el-tooltip effect="dark" content="点击更换头像" placement="top-start">
                        <div @click="uploadAvatarFile" class="image_upload" :class="{
                            'upload-show': uploadAvatar,
                            'upload-hide': !uploadAvatar
                        }">
                            <el-icon>
                                <Picture />
                            </el-icon>
                        </div>
                    </el-tooltip>
                </div>
                <el-form-item label="昵称">
                    <el-input v-model="updateForm.nickname" />
                </el-form-item>
                <el-form-item label="账号">
                    <el-input disabled="true" v-model="user.username" />
                </el-form-item>
                <el-form-item label="密码">
                    <el-input placeholder="请输入密码" type="password" v-model="updateForm.password" show-password />
                </el-form-item>
                <el-form-item label="创建时间">
                    <el-input disabled="true" v-model="user.create_at" />
                </el-form-item>
                <el-form-item label="更新时间">
                    <el-input disabled="true" v-model="user.update_at" />
                </el-form-item>
                <el-form-item style="position: relative;">
                    <el-button style="position: relative; right: 5px;" type="primary" @click="submitForm()">
                        修改账号信息
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>
<style scoped>
#drawer {
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

#outer {
    margin: auto;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-size: 3em;
    font-weight: 900;
}

#avatar {
    position: relative;
    width: 100px;
    height: 100px;
    border-radius: 50px;
    margin-left: 50px;
    margin-bottom: 50px;
    overflow: hidden;
    z-index: 50
}

#uploadAvatar {
    position: relative;
    width: 100px;
    height: 100px;
    margin-top: 50px;
    margin-bottom: 100px;
    border-radius: 50px;
    overflow: hidden;
}

.image_upload {
    position: absolute;
    top: 0px;
    left: 0px;
    width: 100px;
    height: 100px;
    border-radius: 50px;
    overflow: hidden;
    background-color: rgba(60, 60, 60, 0.514);
    display: flex;
    justify-content: center;
    align-items: center;
}

.upload-show {
    z-index: 999
}

.upload-hide {
    z-index: -999
}

#avatar:hover {
    cursor: pointer;

}
</style>